// pages/addGon/index.ts
import { getTokenKey } from "../../utils/auth";
import { getLocationInfo} from "../../utils/location.js";
import { handleFileUploading, deleteFile } from "../../utils/file.js";
import { deleteMarker, deleteFileFromDbs,uploadInitFile, getItemById } from "../../utils/user";

const app = getApp();
Page({
  data: {
    markerId: 0,
    points: [{}],
    description:"",
    imgList:[],
    gonId:0,
    isUpdate:false
  },
  onLoad(options){
    if(options.id){
      this.updateInit(options)
    }else{
      getLocationInfo().then(res=>{
        this.setData({
          points:[{latitude: res.latitude, longitude: res.longitude}] 
        })
      }) 
    } 
  },

  updateInit(options){
    console.log(options)
    this.setData({
      isUpdate: true,
      description: options.description,
      markerId: options.id,
      imgList: options.imageList===undefined ? [] : JSON.parse(decodeURIComponent(options.imageList))
    })
    getItemById(app,"polygon",options.id).then(res=>{
      console.log(res)
      this.setData({
        points: res.points
      })
    })
  },
 

  chooseImage(e){
    this.setData({
      imgList: e.detail
    })
  },

  addPoint() {
    // 获取当前定位
    var that = this
    let points = this.data.points
    wx.showModal({
      title: '提示',
      content: '获取当前位置点',
      success (res) {
        if (res.confirm) {
          getLocationInfo().then(res=>{
            points.push({
              'latitude': res.latitude,
              'longitude': res.longitude
            })
            that.setData({
              points
            })
          }) 
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  deletePoint(e) {
    let {index} = e.target.dataset
    let points = this.data.points
    points = points.filter(item=>{
      return item !== points[index]
    })
    this.setData({points})
  },

  async submitForm(){
    if(this.data.points.length <= 2){
      wx.showModal({
        title: '提示',
        content: '请至少添加三个点',
      })
    }else{
      wx.showLoading({title: '正在提交'})
      const resp = await app.call({
        path:'/polygon/weChat/add',
        method: 'post',
        header: {
          'X-WX-SERVICE': 'fire-assistant-s',
          'tokens': getTokenKey()//必须添加#######
        },
        data: {
          description: this.data.description,
          points: this.data.points
        }
      })
      if(resp.id){
        this.setData({
          gonId: resp.id
        })
        this.uploadFiles()
        wx.hideLoading()
        wx.showModal({
          title: '提交成功',
          content:'提交成功',
          success () { 
            wx.switchTab({
              url: '../index/index',
            })
          }
        })   
      }
    }
  },

  uploadFiles(){
    this.data.imgList.forEach((item)=>{
      let filePath = item.tempFilePath
      let name = filePath.substring(filePath.lastIndexOf('/')+1)
      handleFileUploading(name, item.tempFilePath, app).then((res)=>{
        console.log(res)
      })
      this.uploadInit(item)
    })
  },

  async uploadInit(item){
    let gonId = this.data.gonId
    let filePath = item.tempFilePath
    let size = item.size
    let name = filePath.substring(filePath.lastIndexOf('/')+1)
    let ext = filePath.substring(filePath.lastIndexOf('.')+1)
    const resp = await app.call({
      path:'/files/upload_init',
      method: 'post',
      header: {
        'X-WX-SERVICE': 'fire-assistant-s',
        'tokens': getTokenKey()//必须添加#######
      },
      data: {
        "name": name,
        "size": size,
        "ext": ext,
        "key": name,
        "object_id": gonId,
        "object_type": "polyGon"
      }
    })
    console.log(resp)
  },

    //更新标记
  async updateItem(){
      const itemId = this.data.markerId
      var imgList = this.data.imgList
      if(this.data.points.length <= 2){
        wx.showModal({
          title: '请至少添加三个点',
        })
      }else{
        // 更新基本信息
        this.updateBasicInfo(itemId).then(res => {
          // 数据库中已经存储的，但在客户端被更新后删除的， 需要删除之前存在的
          res.files.forEach(item => {
            let count = 0
            imgList.forEach(image =>{
              if(!image.id || item.id !== image.id){
                count++
              }
            })
            if(count === imgList.length){
              // 删除操作 在数据库中删除 
              deleteFileFromDbs(app, "polyGon", item.id)
              // 删除操作 在cos 中删除
              deleteFile(item, app).then(res=>{
                console.log(res)
              })
            }
          })
          // 添加新图片  在数据库添加和 在对象存储中添加
          imgList.forEach(image =>{
            if(image.tempFilePath){
              let filePath = image.tempFilePath
              let name = filePath.substring(filePath.lastIndexOf('/')+1)
              uploadInitFile(app,"polyGon", image, itemId).then((res)=>{
                if(res.id){
                  handleFileUploading(name, image.tempFilePath, app)
                }
              })
            }
          })
          // 更新成功
          wx.showModal({
            title: '更新成功',
            content: '更新成功',
            complete: () => {
              wx.switchTab({
                url: '../index/index',
              })
            }
          })
        })
      }     
  },
  
    // 更新基本信息
  updateBasicInfo(itemId){
    return new Promise((resolve) => {
      resolve(
        app.call({
          path:`/polygon/${itemId}`,
          method: 'put',
          header: {
            'X-WX-SERVICE': 'fire-assistant-s',
            'tokens': getTokenKey()//必须添加#######
          },
          data: {
            description: this.data.description,
            points: this.data.points
          }
        })
      )
    })
  },
  

  // 完全删除区域
  async deleteItem(){
    var imgList = this.data.imgList
    wx.showModal({
      title: '您确定要删除这个区域标记吗？',
      complete: (res) => {
        if (res.confirm) {
          // 根据markerId删除 数据库中
          deleteMarker(app, "polygon", this.data.markerId).then((res)=>{
            if(res){
              wx.showModal({
                title: '出错了',
                content: res.message ? res.message:res
              })
            }else{
              // 删除对象存储中的照片 可能存在问题
              imgList.forEach(item=>{
                if(item.img){
                  // 对象存储中的照片
                  deleteFile(item, app).then(res=>{
                    console.log(res)
                  })
                }
              })
              wx.showModal({
                title: '删除成功',
                complete: () => {
                  wx.switchTab({
                    url: '../index/index',
                  })
                }
              })
            } 
          })
        }
      }
    })
   
  }

})